package com.resource.base.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.resource.project.entity.RespBean;
import com.resource.project.service.system.service.IHrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录失败处理
 */
@Component
public class AuthenticationLoginFailureHandler implements AuthenticationFailureHandler {
    @Autowired
    private IHrService iHrService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        RespBean respBean = RespBean.build();
        if (e instanceof BadCredentialsException){
            respBean=RespBean.error("用户名或密码错误");
        }else if (e instanceof AuthenticationServiceException){
            respBean=RespBean.error("账号被锁定");
        }
        PrintWriter out = response.getWriter();
        String s = new ObjectMapper().writeValueAsString(respBean);
        out.write(s);
        out.flush();
        out.close();
    }
}
